<template>
  <div class="side-wrapper">
    <logo></logo>
    <scroll-bar class="side-main">
      <el-menu
        :mode="mode"
        :collapse="!collapsed"
        :default-active="$route.path"
        class="el-menu-vertical-demo"
        :unique-opened="true"
        :openeds="openKeys"
        @open="handleOpen"
        @close="handleClose"
        background-color="#545c64"
        text-color="#fff"
        active-text-color="#ffd04b">
        <template v-for="item in baseRoute">
          <!-- item无子元素 且 hidden不为true -->
          <menu-item v-if="!item.children && !item.hidden" :key="item.path" :index="item.path" :currentRoute="item"></menu-item>
          <!-- item有子元素 或 item.hidden为true -->
          <template v-else v-for="temp in item.children">
            <menu-item v-if="!temp.children" :key="temp.path" :index="temp.path" :currentRoute="temp" />
            <sub-menu v-else :key="temp.path" :index="temp.path" :currentRoute="temp" />
          </template>
        </template>
      </el-menu>
    </scroll-bar>
  </div>
</template>

<script>
import logo from './logo.vue'
import { mapGetters } from 'vuex';
import subMenu from './subMenu';
import menuItem from './menuItem';
export default {
  name: 'sideBar',
  props: {
    collapsed: {
      type: Boolean,
      default: true
    },
    mode: {
      type: String,
      default: 'vertical'
    }
  },
  components: {
    logo,
    menuItem,//自定义菜单组件
    subMenu,
  },
  data() {
    return {
      openKeys:[],//控制哪些子菜单是展开的
    }
  },
  computed: {
    ...mapGetters(['baseRoute'])
  },
  mounted() {
    let matched = this.$route.matched.filter(item => item.meta && item.meta.title);
    if (matched.length > 1) {
      this.openKeys = matched.map(item => item.path);
    }
  },
  methods: {
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
      // 找到当前打开的子菜单中，哪一个是没有在 openKeys 数组中出现过的
      const currentOpenKey = this.openKeys.indexOf(key) === -1 ? key : null;
      // 更新 openKeys 数组
      if (currentOpenKey) {
        this.openKeys.push(currentOpenKey);
      }
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
      // 从 openKeys 数组中移除当前关闭的子菜单索引
      const index = this.openKeys.indexOf(key);
      if (index !== -1) {
        this.openKeys.splice(index, 1);
      }
    }
  },
  mounted() {
    console.log('baseRoute',this.baseRoute);
  }
}
</script>

<style>

</style>